package com.lc.luzhengtang.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.esafirm.imagepicker.features.ImagePicker;
import com.esafirm.imagepicker.model.Image;
import com.google.gson.Gson;
import com.lc.luzhengtang.BaseApplication;
import com.lc.luzhengtang.R;
import com.lc.luzhengtang.adapter.CommentAdapter;
import com.lc.luzhengtang.base.BaseActivity;
import com.lc.luzhengtang.bean.CommentBean;
import com.lc.luzhengtang.bean.CommentGetBean;
import com.lc.luzhengtang.bean.EvaluateBean;
import com.lc.luzhengtang.conn.ConnEvalute;
import com.zcx.helper.http.AsyCallBack;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.Callback;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class EvaluateActivity extends BaseActivity implements CommentAdapter.OnItemClickListener, com.lc.luzhengtang.interfaces.NoticeActivity<Integer> {

    public static final String KEY_IDS = "KEY_IDS";
    public static final String KEY_PICS = "KEY_PICS";
    public static final String KEY_ORDERSN = "KEY_ORDERSN";

    private static final int REQUEST_CODE_PICKER = 1;
    private static final String TAG = "EvaluateActivity";
    private static final int SEND_ERROR = 2;

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.rl_head)
    RelativeLayout rlHead;
    @BindView(R.id.bn_submit)
    Button bnSubmit;
    @BindView(R.id.iv_anonymous)
    ImageView ivAnonymous;
    @BindView(R.id.ll_anonymous)
    LinearLayout llAnonymous;
    @BindView(R.id.rl_foot)
    RelativeLayout rlFoot;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;

    private List<CommentBean> list = new ArrayList<>();
    private CommentAdapter adapter;

    private List<String> cacheImage = new ArrayList<>();

    private EvaluateBean bean = new EvaluateBean();

    private int curPicsId = -1;
    private String orderSn;
    private ProgressDialog dialog;

    List<String> comment = new ArrayList<>();


    List<CommentGetBean.DataBean> dataBeanList = new ArrayList<>();
    public List<String> goodslist = new ArrayList<>();

    private static final int SEND_SUCCESS = 1;
/*
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
//            dialog.dismiss();
           if (msg.what == SEND_SUCCESS) {
                String json = (String) msg.obj;
                SimpleBean simpleBean = new Gson().fromJson(json, SimpleBean.class);
                if (simpleBean.getCode() == 200) {

                } else {

                }*//*
//                Toast.makeShortText(simpleBean.getMessage());
               *//* if (list.get(0).getCode() == 200) {
                    Intent intent = new Intent(PingjiaActivity.this, MineOrderActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putInt(MineOrderActivity.POSITION_KEY, 3);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }*//*
            } else {
//                Toast.makeShortText("发布失败，请检查网络");
            }
        }
    };*/

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_evaluate);
        ButterKnife.bind(this);
        Bundle bundle = getIntent().getExtras();
        orderSn = bundle.getString(KEY_ORDERSN);

        adapter = new CommentAdapter(this, this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(adapter);

        getCommentData();
//        initDatas();
        initDatas();

    }

    private void initDatas() {
//              Bundle bundle = getIntent().getExtras();
//        ArrayList<String> picList = bundle.getStringArrayList(KEY_PICS);
//        ArrayList<Integer> idList = bundle.getIntegerArrayList(KEY_IDS);
//        for (int i = 0; i < picList.size(); i++) {
////            list.add(new CommentBean(idList.get(i), 2, picList.get(i), "", new ArrayList<String>()));
//            list.add(new CommentBean(Integer.valueOf(goodslist.get(i)), 2, picList.get(i), "", new ArrayList<String>()));
//        }
//
//        adapter = new CommentAdapter(this, this);
//        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
//        recyclerView.setLayoutManager(linearLayoutManager);
//        recyclerView.setAdapter(adapter);
//
//        adapter.setDatas(list);
//
        bean.setMember_id(BaseApplication.basePreferences.readUid());
        bean.setAnonymous("0");

    }

    @OnClick({R.id.iv_back, R.id.bn_submit, R.id.ll_anonymous})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.bn_submit:
                if (checkParams())
                    submit();
                else {
                    Toast.makeText(EvaluateActivity.this, "请补全评价内容", Toast.LENGTH_SHORT).show();
                }
//                if (comment.isEmpty()){
//                    LovelyToast.makeText(EvaluateActivity.this, "请填评价内容", 0, LovelyToast
//                            .SUCCESS, LovelyToast.SCALE);
//                }else {
//
//                }

                break;
            case R.id.ll_anonymous:
                ivAnonymous.setSelected(!ivAnonymous.isSelected());
                bean.setAnonymous(ivAnonymous.isSelected() ? "1" : "0");
//                startActivity(new Intent(AddressManageActivity.this, AddAddress.class));

                break;
        }
    }

    private boolean checkParams() {
        boolean b = true;

        for (CommentBean next : list) {
            if (TextUtils.isEmpty(next.getComment())) {
                b = false;
                break;
            }
        }
        return b;
    }

    private void submit() {
        showLoading();
        List<EvaluateBean.CommentBean> list = new ArrayList<>();
        Map<String, File> fileMap = new LinkedHashMap<>();
        for (int i = 0; i < this.list.size(); i++) {
            CommentBean commentBean = this.list.get(i);
            EvaluateBean.CommentBean bean = new EvaluateBean.CommentBean();
            bean.setGoods_id(String.valueOf(commentBean.getId()));
            bean.setContent(commentBean.getComment());
            bean.setEvaluate(String.valueOf(commentBean.getEvaluate()));
            List<String> picUrls = commentBean.getPicUrls();
            bean.setNumber(picUrls.size());
            bean.setOrdersn(orderSn);
            for (int j = 0; j < picUrls.size(); j++) {
                fileMap.put("picarr" + i + (j + 1), new File(picUrls.get(j)));
            }

            list.add(bean);
        }
        this.bean.setComment(list);

        Map<String, String> params = new HashMap<>();
        params.put("data", new Gson().toJson(bean));

//
//        OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
//        httpClientBuilder.connectTimeout(5, TimeUnit.SECONDS);
//        httpClientBuilder.addInterceptor(new Interceptor() {
//            @Override
//            public Response intercept(Chain chain) throws IOException {
//
//                Request original = chain.request();
//
//                HttpUrl url = original.url();
//                Log.d(TAG, "url = " + url.url());
//
//                Request request = original.newBuilder()
//                        .header("postman-token", "e22671c2-56b1-2c77-4d0f-3729bf128b2b")
//                        .header("Authorization", "Basic " + BaseApplication.basePreferences.getToken())
//                        .header("AppVersion", BaseApplication.basePreferences.getVersionName())
//                        .method(original.method(), original.body())
//                        .build();
//
//
//                return chain.proceed(request);
//            }
//        });


        PostFormBuilder params1 = OkHttpUtils.post()//
                .url("http://luzhengtang.cn/index.php/api/evaluate/gappraise")
                .params(params);

        Set<Map.Entry<String, File>> entries = fileMap.entrySet();
        for (Map.Entry<String, File> entry : entries) {
            params1.addFile(entry.getKey(), entry.getValue().getAbsolutePath(), entry.getValue());
        }
        params1.build().execute(new Callback() {
            @Override
            public Object parseNetworkResponse(okhttp3.Response response, int id) throws Exception {
                dismissLoading();
/*
                String string = response.body().string();
                Message message = handler.obtainMessage();
                message.what = SEND_SUCCESS;
                message.obj = string;
                handler.sendMessage(message);*/


                return null;


            }

            @Override
            public void onError(okhttp3.Call call, Exception e, int id) {
                dismissLoading();
               /* Message message = handler.obtainMessage();
                message.what = SEND_ERROR;
                handler.sendMessage(message);*/
            }

            @Override
            public void onResponse(Object response, int id) {
                dismissLoading();
            }


            @Override
            public void onAfter(int id) {
                super.onAfter(id);
                dismissLoading();


                finish();
            }
        });

//        params1//

//                .addFile("mFile", "messenger_01.png", file)//
//                .addFile("mFile", "test1.txt", file2)//
//                .build()//
//                .execute(new MyStringCallback());
    }

    @Override
    public void onGoodClick(CommentBean bean) {
        bean.setEvaluate(1);
        adapter.setDatas(list);
    }

    @Override
    public void onMidClick(CommentBean bean) {
        bean.setEvaluate(2);
        adapter.setDatas(list);
    }

    @Override
    public void onBadClick(CommentBean bean) {
        bean.setEvaluate(3);
        adapter.setDatas(list);
    }

    @Override
    public void onAddPicClick(CommentBean bean) {
        curPicsId = bean.getId();
        List<String> picUrls = bean.getPicUrls();
        if (picUrls.size() < 4) {
            ImagePicker.create(this).multi().limit(4 - picUrls.size()).returnAfterFirst(false).start(REQUEST_CODE_PICKER);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_PICKER && resultCode == RESULT_OK && data != null) {
            ArrayList<Image> images = (ArrayList<Image>) ImagePicker.getImages(data);
            if (images.size() > 0) {
                cacheImage.clear();
                for (Image image : images) {
                    cacheImage.add(image.getPath());
                }
                Log.d(TAG, "cacheImage = " + cacheImage);
                for (CommentBean bean : list) {
                    if (bean.getId() == curPicsId) {
//                        bean.getPicUrls().clear();
                        bean.getPicUrls().addAll(cacheImage);
                        break;
                    }
                }
                adapter.setDatas(list);
            }
            return;
        }

    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }

    @Override
    public void onRefresh(Integer integer) {

    }

    public void getCommentData() {
        new ConnEvalute(orderSn, new AsyCallBack<CommentGetBean>() {
            @Override
            public void onStart(int type) throws Exception {
                super.onStart(type);
            }

            @Override
            public void onSuccess(String toast, int type, Object o, CommentGetBean commenBean) throws Exception {
                super.onSuccess(toast, type, o, commenBean);
                dataBeanList = commenBean.getData();
                for (int i = 0; i < dataBeanList.size(); i++) {
                    CommentGetBean.DataBean dataBean = dataBeanList.get(i);
//                    dataBeanList.add(dataBeanList.get(i).getGoods_id());
//                    list.add(new CommentBean(Integer.parseInt(dataBean.getGoods_id()), 2, dataBean.getPicurl(), "", new ArrayList<String>()));
                    list.add(new CommentBean(Integer.parseInt(dataBean.getGoods_id()), 1, dataBean.getPicurl(), "", new ArrayList<String>()));
//                    goodslist.add(dataBeanList.get(i).getGoods_id());
                }
                adapter.setDatas(list);

            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
//                initDatas();
            }
        }


        ).execute(EvaluateActivity.this, false);


    }


}
